import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

// 获取二级路由部署路径，与 vite.config.ts 中的 base 保持一致
const getBasePath = (): string => {
  // 从环境变量获取
  const envBase = import.meta.env.VITE_BASE_URL
  if (envBase) {
    // 确保以 / 开头，以 / 结尾（除了根路径）
    let base = envBase.startsWith('/') ? envBase : `/${envBase}`
    if (base !== '/' && !base.endsWith('/')) {
      base = `${base}/`
    }
    return base
  }
  // 默认根路径
  return '/'
}

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: () => import('@/layouts/MainLayout.vue'),
    redirect: { name: 'Dashboard' },
    meta: { requiresAuth: true },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '仪表盘', icon: 'Odometer' }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('@/views/Profile.vue'),
        meta: { title: '个人中心', icon: 'User' }
      },
      {
        path: 'members',
        name: 'Members',
        component: () => import('@/views/Members.vue'),
        meta: { title: '会员管理', icon: 'UserFilled' }
      },
      {
        path: 'member-levels',
        name: 'MemberLevels',
        component: () => import('@/views/MemberLevels.vue'),
        meta: { title: '会员等级', icon: 'Trophy' }
      },
      {
        path: 'blogs',
        name: 'Blogs',
        component: () => import('@/views/Blogs.vue'),
        meta: { title: '博客管理', icon: 'Document' }
      },
      {
        path: 'blogs/:id',
        name: 'BlogDetail',
        component: () => import('@/views/BlogDetail.vue'),
        meta: { title: '博客详情', hidden: true }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(getBasePath()),
  routes
})

// 路由守卫
router.beforeEach((to, _from, next) => {
  const authStore = useAuthStore()
  
  if (to.meta.requiresAuth && !authStore.isAuthenticated) {
    // 使用命名路由，避免 base path 问题
    next({ name: 'Login', query: { redirect: to.fullPath } })
  } else if (to.name === 'Login' && authStore.isAuthenticated) {
    // 使用命名路由重定向到首页
    next({ name: 'Dashboard' })
  } else {
    next()
  }
})

export default router

